<template>
  <div ref="containerRef" class="h-full overflow-auto p-4 bg-gray-100" @scroll.passive="onScroll">
    <div v-if="loadingMore" class="text-center text-sm text-gray-500 my-2">加载中...</div>

    <div v-for="msg in messages" :key="msg.id" class="mb-4 flex flex-col">
      <div class="text-sm text-gray-400 mb-1">{{ msg.role === 'user' ? '你' : 'AI' }}</div>

      <div class="relative bg-white p-3 rounded shadow prose prose-sm max-w-full overflow-hidden">
        <div v-if="msg.role === 'ai' && msg.loading">
          {{ msg.displayText }}
          <span class="animate-pulse">|</span>
        </div>
        <div v-else v-html="renderMarkdown(msg.content)" />
      </div>

      <div v-if="msg.role === 'ai'" class="text-xs mt-1 flex gap-2 text-blue-500">
        <span class="cursor-pointer" @click="copyText(msg.content)">复制</span>
        <span class="cursor-pointer" @click="regenerate(msg.id)">重新回答</span>
        <span class="cursor-pointer text-red-500" @click="remove(msg.id)">删除</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { marked } from 'marked'

const props = defineProps({
  loadHistory: Function, // () => Promise<msg[]>
})

const containerRef = ref(null)
const messages = ref([])
const loadingMore = ref(false)
let hasMore = true

// 监听滚动，顶部时加载历史
const onScroll = async () => {
  const el = containerRef.value
  if (!el || loadingMore.value || !hasMore) return

  if (el.scrollTop < 50) {
    loadingMore.value = true
    const oldHeight = el.scrollHeight
    const history = await props.loadHistory()
    if (history.length === 0) hasMore = false
    messages.value = [...history, ...messages.value]
    await nextTick()
    el.scrollTop = el.scrollHeight - oldHeight
    loadingMore.value = false
  }
}

// 添加新消息并自动滚动到底部
const addMessage = (msg) => {
  console.log(msg);
  messages.value.push(msg)
  nextTick(() => {
    const el = containerRef.value
    el.scrollTop = el.scrollHeight
  })
}

// 逐字加载回答
const simulateTyping = async (fullText, id) => {
  let current = ''
  for (let i = 0; i < fullText.length; i++) {
    await new Promise(r => setTimeout(r, 20)) // 控制字速
    current += fullText[i]
    const msg = messages.value.find(m => m.id === id)
    if (msg) msg.displayText = current
  }
  const msg = messages.value.find(m => m.id === id)
  if (msg) {
    msg.loading = false
    msg.content = fullText
  }
}

// 功能：复制、删除、重答
const copyText = (text) => {
  navigator.clipboard.writeText(text)
  alert('已复制')
}

const remove = (id) => {
  messages.value = messages.value.filter(m => m.id !== id)
}

const regenerate = (id) => {
  const index = messages.value.findIndex(m => m.id === id)
  if (index !== -1) {
    messages.value.splice(index, 1)
    // 假设重新调用接口，此处模拟
    simulateAIReply('这是新的回答...', id + '-re')
  }
}

// 渲染 markdown
const renderMarkdown = (text) => {
  return marked.parse(text || '')
}

// 模拟 AI 回答
const simulateAIReply = (text, id) => {
  const msg = {
    id,
    role: 'ai',
    content: '',
    displayText: '',
    loading: true,
  }
  addMessage(msg)
  simulateTyping(text, id)
}

// 初始模拟数据
onMounted(() => {
  console.log(123);
  addMessage({ id: 'u1', role: 'user', content: '你好' })
  simulateAIReply('你好，我是 AI。有什么可以帮你的吗？', 'a1')
})
</script>

<style scoped>
.prose code {
  background: #f3f4f6;
  padding: 2px 4px;
  border-radius: 4px;
}
</style>
